#!/bin/bash

# 初始化统计变量
total_count=0       # 总包数
success_count=0     # 成功数
fail_count=0        # 失败数

# 检查是否安装了rpmrebuild
if ! command -v rpmrebuild &> /dev/null; then
    echo "错误：未找到rpmrebuild工具，请先安装 (yum install rpmrebuild)"
    exit 1
fi

# 先统计当前目录下的有效RPM包总数（提前计数，避免循环中重复判断）
for rpm_file in *.rpm; do
    if [ -f "$rpm_file" ] && [[ "$rpm_file" == *.rpm ]]; then
        ((total_count++))
    fi
done

# 提示开始处理
echo "========================================"
echo "开始批量处理RPM包 → 共发现 $total_count 个有效RPM包"
echo "========================================"
echo

# 循环处理当前目录下所有RPM包
for rpm_file in *.rpm; do
    # 检查是否是有效文件（排除目录或非.rpm文件）
    if [ -f "$rpm_file" ] && [[ "$rpm_file" == *.rpm ]]; then
        echo "【当前处理】：$rpm_file"
        
        # 核心操作：修改Release和Packager（避免重复）
        rpmrebuild --change-spec-preamble='sed -e "s/^\(Release:\s*.*\)oe2403/\1ky11/" -e "s/^\(Release:\s*\)\([0-9.]\+\)$/\1\2.ky11/" -e "s/^\(Release:\s*.*\)\(\.ky11\)\{2,\}$/\1.ky11/" -e "/^Packager:/d" -e "/^Name:/aPackager: ISCAS"' -p "$rpm_file" >/dev/null 2>&1
        
        # 统计成功/失败数量
        if [ $? -eq 0 ]; then
            ((success_count++))
            echo "【结果】✅ 处理成功 → 新包路径：~/rpmbuild/RPMS/x86_64/"
        else
            ((fail_count++))
            echo "【结果】❌ 处理失败（可能是包损坏或依赖缺失）"
        fi
        echo "----------------------------------------"
    fi
done

# 输出最终统计报告
echo "========================================"
echo "批量处理完成！【统计结果】"
echo "----------------------------------------"
echo "总处理包数：$total_count 个"
echo "成功处理：$success_count 个"
echo "失败处理：$fail_count 个"
echo "----------------------------------------"
echo "新包默认存放路径：~/rpmbuild/RPMS/x86_64/"
echo "提示：失败包可尝试执行 yum builddep 包名 安装依赖后重试"
echo "========================================"